package com.seabook.happy.website.servlets;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.seabook.happy.website.pojos.CaptchaImage;
import com.seabook.happy.website.services.SimpleCaptchaService;

public class CaptchaServiceServlet extends HttpServlet {
	private SimpleCaptchaService scs = new SimpleCaptchaService();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String reqParam = req.getParameter("captcha");
		OutputStream output = resp.getOutputStream();
		if (reqParam != null && !"".equals(reqParam.trim())) {
			int inputLength = reqParam.length();
			if (inputLength == 0) output.write("1".getBytes());
			String storedCaptcha = (String) req.getSession(true).getAttribute("captcha");
			System.out.println(storedCaptcha + "================ in Session");
			String compareValue = storedCaptcha.substring(0, inputLength); 
			System.out.println(compareValue);
			if (reqParam.equals(compareValue)) {
				output.write("1".getBytes());
			}
			else {
				output.write("0".getBytes());
			}
			
		} else {
			if (scs.generateCaptchaImage()) {
				CaptchaImage image = CaptchaImage.getCaptchaImage();
				req.getSession(true).setAttribute("captcha", image.getCaptcha());
		        output.write(image.getImage().getImageData());
			}
		}
		   output.flush();
	}
}
